<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Title</title>
	<script src="lib/socket.io.min.js"></script>
</head>
<body>
	<div id="login">
		<input placeholder="请输入您的昵称，回车进行登陆" type="text">
	</div>
	<div id="room">
		<h3>欢迎<span style="color:red">zhangsan</span>来到直接间，当前直接间人数<span style="color:green;">1</span></h3>
		<hr/>
		<input  type="text"><button>提交</button>
		<hr/>
		<textarea id="roomText" cols="100" rows="100"></textarea>
	</div>
</body>
<script>
	const login = document.querySelector("#login");
	const room = document.querySelector("#room");
	const roomText = document.querySelector("#roomText");
	const btn = document.querySelector("button");
	room.style.display = "none";
	login.querySelector("input").onkeyup = async function(e){
		if(e.keyCode === 13){
			const userName = e.target.value.trim();
			if(userName.length<4){
				alert("昵称长度不允许小于4");
				return;
			}
			const {ok} = await fetch("/login?userName="+e.target.value).then(value=>value.json());
			if(ok === 1){
				// 进入房间
				login.style.display = "none";
				room.style.display = "block";
				
				const spans = room.querySelectorAll("span");
				spans[0].innerHTML = userName;
				
				const ws = io.connect("/");
				ws.emit("intoRoom",userName);
				ws.on("inlineNum",function(userName,num,isInto){
					console.log(1111)
					spans[1].innerHTML = num;// 更新在线人数
					if(isInto){
						console.log(1111,roomText.innerText)
						roomText.value = userName+"进入了房间\n"+roomText.value;
					}else{
						roomText.value = userName+"离开了房间\n"+roomText.value;
					}
				})
				ws.on("roomSay",function(userName,sayText){
					roomText.value = userName+"说："+sayText+"\n"+roomText.value;
				})
				
				btn.onclick = function(){
					const sayText = room.querySelector("input").value.trim();
					if(sayText.length<5){
						alert("您说的太短了！");
						return;
					}
					ws.emit("say",userName,sayText);
				}
				
				
			}else{
				alert("房间内不允许出现相同名字的昵称")
			}
		}
	}
</script>
</html>